using System;
using System.Collections;
using System.Collections.Generic;
using Main.Audio;
using Main.Details;
using Main.Event;
using Unity.Mathematics;
using UnityEngine;
using ZSW.Framework;

namespace Main.CropPlant
{
    public class Crop : MonoBehaviour
    {
        public CropDetails cropDetails;
        public TileDetails tileDetails;
        public bool IsHarvest => tileDetails.growDays >= cropDetails.DayAmount;
        private int harvestActionCount;
        public Animator animator;

        /// <summary>
        /// 处理工具操作
        /// </summary>
        /// <param name="tool"></param>
        internal void ProcessToolAction(ItemDetails tool, TileDetails tileDetails)
        {
            int requireTimes = cropDetails.GetToolRequireTimes(tool.ItemID);

            this.tileDetails = tileDetails;

            if (requireTimes < 0)
            {
                return;
            }

            animator = GetComponentInChildren<Animator>();

            if (harvestActionCount < requireTimes)
            {
                harvestActionCount++;

                // TODO:声音 粒子效果
                if (animator != null)
                {
                    if (Player.Transform.position.x > transform.position.x)
                    {
                        animator.SetTrigger("RotateLeft");
                    }
                    else
                    {
                        animator.SetTrigger("RotateRight");
                    }
                }

                if (cropDetails.hasParticleEffect)
                {
                    MainEventSystem.CallParticleEffectEvent(cropDetails.partialEffectType, transform.position + cropDetails.effectPos);
                }

                if (cropDetails.soundEffect != SoundName.None)
                {
                    MainEventSystem.CallPlaySoundEvent(cropDetails.soundEffect);
                }
            }

            if (harvestActionCount >= requireTimes)
            {
                if (cropDetails.generateAtPlayPosition || !cropDetails.hasAnimation)
                {
                    // 生成农作物
                    SpawnHarvestItems();
                }
                else if (cropDetails.hasAnimation)
                {
                    if (Player.Transform.position.x > transform.position.x)
                    {
                        animator.SetTrigger("FallingLeft");
                    }
                    else
                    {
                        animator.SetTrigger("FallingRight");
                    }
                    MainEventSystem.CallPlaySoundEvent(SoundName.TreeFalling);
                    StartCoroutine(HarvestAfterAnimator());
                }
            }
        }


        private IEnumerator HarvestAfterAnimator()
        {
            while (!animator.GetCurrentAnimatorStateInfo(0).IsName("End"))
            {
                Debug.Log("wait");
                yield return null;
            }

            SpawnHarvestItems();

        }

        /// <summary>
        /// 生成农作物
        /// </summary>
        public void SpawnHarvestItems()
        {
            for (int i = 0; i < cropDetails.productItemIDs.Length; i++)
            {
                int itemID = cropDetails.productItemIDs[i];
                int minAmount = cropDetails.productItemMinAmounts[i];
                int maxAmount = cropDetails.productItemMaxAmounts[i];

                int amount = UnityEngine.Random.Range(minAmount, maxAmount + 1);

                // 循环生成指定数量的物品
                for (int j = 0; j < amount; j++)
                {
                    //
                    if (cropDetails.generateAtPlayPosition)
                    {
                        MainEventSystem.HarvestAtPlayerPositionEvent(itemID);
                    }
                    // 世界中生成物品
                    else
                    {
                        var dirX = transform.position.x - Player.Transform.position.x > 0 ? 1 : -1;

                        var spawnPos = new Vector3(transform.position.x + UnityEngine.Random.Range(0f, cropDetails.spawnRadius.x * dirX),
                        transform.position.y + UnityEngine.Random.Range(-cropDetails.spawnRadius.y, cropDetails.spawnRadius.y), 0);

                        MainEventSystem.CallInstantiateItemEvent(cropDetails.productItemIDs[i], spawnPos);
                    }
                }
            }

            if (tileDetails != null)
            {
                tileDetails.daysSinceLastHarvest++;

                // 重复生长判断(TODO: 猜测第二判断存在问题)
                if (cropDetails.daysToRegrow > 0 && tileDetails.daysSinceLastHarvest < cropDetails.regrowTimes)
                {
                    // 地图已种植日期 = 总种植日期 - 重复生成时间
                    tileDetails.growDays = cropDetails.DayAmount - cropDetails.daysToRegrow;
                }
                else if (cropDetails.transferItemID > 0)
                {
                    tileDetails.seedItemID = cropDetails.transferItemID;
                    tileDetails.daysSinceLastHarvest = -1;
                    tileDetails.growDays = 0;
                }
                // 不允许重复生长
                else
                {
                    tileDetails.daysSinceLastHarvest = -1;
                    tileDetails.seedItemID = -1;
                    // OPTIONAL
                    // tileDetails.daysSinceDug = -1;
                }

                MainEventSystem.CallRefreshMapEvent();

                Destroy(this.gameObject);
            }
        }
    }
}
